package com.example.guiguiapplicatio.fragment.FamilySigning;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.guiguiapplicatio.api.InsertFamilySigningApi;
import com.example.guiguiapplicatio.api.Interface.AllCallback;
import com.example.guiguiapplicatio.MainActivity;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.FamilyarChooseService;
import com.example.guiguiapplicatio.SignatureActivity;

import com.example.guiguiapplicatio.util.ResponseBody;
import com.example.guiguiapplicatio.utils.PreferencesUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.refactor.lib.colordialog.PromptDialog;

public class FamilySigingNextActivity extends AppCompatActivity implements
        View.OnClickListener{
    private final int INSPECTED_CODE = 1; // 被检查人签名意图代码
    private final int INSPECTOR_CODE = 2; // 检查人签名意图代码
    private ImageView stakeholdersSignImageView, beneficiarySignImageView;
    private InsertFamilySigningApi insertFamilySigningApi;
    private Button confirmTheContract;

    private String intentHouseholdName;
    private int intentFamilyNum;
    private String intentHouseholdPhone;
    private String intentHouseholdAddress;
    private String intentStaTime;
    private String intentEndTime;
    private String memberName;
    private List<FamilyarChooseService> familyarchooseserviceList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_family_file_next);
        intentHouseholdName = getIntent().getStringExtra("intentHouseholdName");
        intentFamilyNum = getIntent().getIntExtra("intentFamilyNum", 0);
        intentHouseholdPhone = getIntent().getStringExtra("intentHouseholdPhone");
        intentHouseholdAddress = getIntent().getStringExtra("intentHouseholdAddress");
        intentStaTime = getIntent().getStringExtra("intentStaTime");
        intentEndTime = getIntent().getStringExtra("intentEndTime");
        memberName = getIntent().getStringExtra("memberName");
        String familyarchooseserviceListString = getIntent().getStringExtra("familyarchooseserviceList");
        Type listType = new TypeToken<ArrayList<FamilyarChooseService>>(){}.getType();
        familyarchooseserviceList = new Gson().fromJson(familyarchooseserviceListString, listType);
        if (memberName != null && memberName.startsWith("[") && memberName.endsWith("]")) {
            memberName = memberName.substring(1, memberName.length() - 1);
        }
        List<String> memberNameList = Arrays.asList(memberName.split(","));
        int member_number = memberNameList.size();
        EditText beneficiary_editText = findViewById(R.id.beneficiary_et);
        EditText beneficiary_phone_editText = findViewById(R.id.et_beneficiary_phone);
        EditText data_editText = findViewById(R.id.data_et);
        EditText text_member_number_et = findViewById(R.id.text_member_number_et);
        EditText member_et = findViewById(R.id.member_et);
        EditText et_address = findViewById(R.id.et_address);
        beneficiary_editText.setInputType(InputType.TYPE_NULL);
        beneficiary_phone_editText.setInputType(InputType.TYPE_NULL);
        data_editText.setInputType(InputType.TYPE_NULL);
        text_member_number_et.setInputType(InputType.TYPE_NULL);
        member_et.setInputType(InputType.TYPE_NULL);
        et_address.setInputType(InputType.TYPE_NULL);
        beneficiary_editText.setText(intentHouseholdName);
        beneficiary_phone_editText.setText(intentHouseholdPhone);
        et_address.setText(intentHouseholdAddress);
        member_et.setText(memberName);
        text_member_number_et.setText(Integer.toString(member_number));
        data_editText.setText(intentStaTime + "-" + intentEndTime);
        stakeholdersSignImageView = findViewById(R.id.stakeholders_sign_image_view);  // 被检查单位（人）签名
        beneficiarySignImageView = findViewById(R.id.beneficiary_sign_image_view);  // 检查人签名
        confirmTheContract = findViewById(R.id.confirm_the_contract);
        // 设置监听器confirm_the_contract
        stakeholdersSignImageView.setOnClickListener(this);    // 获取被检查单位（人）签字
        beneficiarySignImageView.setOnClickListener(this);
        confirmTheContract.setOnClickListener(this);
    } // onCreate-end
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.stakeholders_sign_image_view) {  // 被检查单位（人）签名
            Intent intent = new Intent(this, SignatureActivity.class);
            startActivityForResult(intent, INSPECTED_CODE); // 获取被检查单位（人）手写签名
        } else if (v.getId() == R.id.beneficiary_sign_image_view) {  // 被检查人签名
            Intent intent = new Intent(this, SignatureActivity.class);
            startActivityForResult(intent, INSPECTOR_CODE);  // 获取检查人手写签名
        }else if (v.getId() == R.id.confirm_the_contract) {
            if (stakeholdersSignImageView.getDrawable() == null || beneficiarySignImageView.getDrawable() == null) {
                // 如果没有签名，则提醒用户
                new PromptDialog(this)
                        .setDialogType(PromptDialog.DIALOG_TYPE_WARNING)
                        .setAnimationEnable(true)
                        .setTitleText("Warning")
                        .setContentText("请确保被检查单位（人）和检查人都已签名")
                        .setPositiveListener("OK", new PromptDialog.OnPositiveListener() {
                            @Override
                            public void onClick(PromptDialog dialog) {
                                dialog.dismiss();
                            }
                        }).show();
                return;
            }
            else {
                View confirmButton = findViewById(R.id.confirm_the_contract);
                confirmButton.setVisibility(View.GONE);
                View ve = getWindow().getDecorView();
                Bitmap bitmap = Bitmap.createBitmap(ve.getWidth(), ve.getHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas();
                canvas.setBitmap(bitmap);
                ve.draw(canvas);
                insertFamilySigningApi = new InsertFamilySigningApi(new AllCallback() {
                    @Override
                    public void onSuccess(ResponseBody<Object> responseBody) throws ParseException {
                        if(responseBody.getCode() == 200){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    new PromptDialog(FamilySigingNextActivity.this)
                                            .setDialogType(PromptDialog.DIALOG_TYPE_INFO)
                                            .setAnimationEnable(true)
                                            .setTitleText("INFO")
                                            .setContentText("签约成功返回首页")
                                            .setPositiveListener("OK", new PromptDialog.OnPositiveListener() {
                                                @Override
                                                public void onClick(PromptDialog dialog) {
                                                    Intent intent = new Intent(FamilySigingNextActivity.this, MainActivity.class);
                                                    intent.putExtra("id",1);
                                                    startActivity(intent);
                                                    dialog.dismiss();
                                                }
                                            }).show();
                                }
                            });
                        }
                        else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    new PromptDialog(FamilySigingNextActivity.this)
                                            .setDialogType(PromptDialog.DIALOG_TYPE_WRONG)
                                            .setAnimationEnable(true)
                                            .setTitleText("WRONG")
                                            .setContentText("签约失败")
                                            .setPositiveListener("OK", new PromptDialog.OnPositiveListener() {
                                                @Override
                                                public void onClick(PromptDialog dialog) {
                                                    dialog.dismiss();
                                                }
                                            }).show();
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(String errorMessage) {

                    }
                });
                insertFamilySigningApi.performPostImg(bitmap,"/storage/emulated/0/Download/image.jpg",familyarchooseserviceList,intentStaTime,intentEndTime, PreferencesUtil.getInt(this,"doctor_id"));
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (intent != null && resultCode == Activity.RESULT_OK && requestCode == INSPECTED_CODE) {
            // 取回被检查单位（人）手写签名
            byte[] bytes = intent.getByteArrayExtra("bitmapbytes");
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            stakeholdersSignImageView.setImageBitmap(bitmap);
        } else if (intent != null && resultCode == Activity.RESULT_OK && requestCode == INSPECTOR_CODE) {
            // 取回检查人手写签名
            byte[] bytes = intent.getByteArrayExtra("bitmapbytes");
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            beneficiarySignImageView.setImageBitmap(bitmap);
        }
    }
}
